<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Designspace extends CI_Controller {
	var $key = '设计空间';
	var $defaultTag = 'home';

	
	public function index()
	{
		$tag = $this->input->get_post('tag');
		if(empty($tag)){
			$tag = $this->defaultTag;
		}
		
		$designspaces = $this->getDesignspaces();
		if(empty($designspaces)){
			return;
		}
		
		$designspace = $this->getDesignspace($designspaces, $tag);
		if(empty($designspace)){
			return;
		}
		
		$pKeys = $this->getPKeys($designspace);
		$pics = $this->getDesignspacePics($pKeys);
		
		$this->load->config('company');
		$data['company'] = $this->config->item('company');
		
		$data['pics'] = $pics;
		$data['designspaces'] = $designspaces;
		$data['designspace'] = $designspace;
		$data['key'] = $this->key;
		
		$this->load->view('/designspace/index', $data);	
	}
	
	private function getDesignspaces(){
		$this->load->config('designspace');
		return $this->config->item('designspace');
	}
	
	private function getDesignspace($all, $tag){
		while( ! empty($all)){
			$tmp = array();
			foreach ($all as $item){
				if($item['tag'] == $tag){
					return $item;
				}
				
				if( ! empty($item['sub'])){
					$tmp = array_merge($tmp, $item['sub']);
				}
			}
			
			 $all = $tmp;
		}
		
		return null;
	}

	private function getPKeys($item){
		if(empty($item)){
			return null;
		}
		
		if( ! empty($item['pKey'])){
			return array($item['pKey']);
		}
		
		if(empty($item['sub'])){
			return null;
		}
		
		$pKeys = array();
		$subItems = $item['sub'];
		
		while( ! empty($subItems)){
			$tmp = array();
			foreach ($subItems as $subItem){
				if( ! empty($subItem['pKey'])){
					$pKeys[] = $subItem['pKey'];
				}
				
				if( ! empty($subItem['sub'])){
					$tmp = array_merge($tmp, $subItem['sub']);
				}
			}
			
			 $subItems = $tmp;
		}
		
		return $pKeys;
	}
	
	private function getDesignspacePics($pKeys){
		$this->load->config('pic');
		$pics = $this->config->item('pic');
		
		$rs = array();
		foreach ($pKeys as $key){
			if(isset($pics[$key])){
				$rs = array_merge($rs, $pics[$key]);
			}				
		}
		
		return $rs; 
	}
}